<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
import { exportToExcel } from '@/utils/exportUtils'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '支付流水' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  goods_all:[],
  flag_data:[{id:1,name:"储值金"},{id:0,name:"普通"}],
  is_check_data:[{id:1,name:"未收银"},{id:2,name:"已收银"}],
  select_customers:[],
  search_loading:false,
  show_detail:false,
  show_data:[],
  detail:[],
  show_refund:false,
  refundForm:{
    refund_price:0,
    refund_remark:"",
    refund_time:new Date().toISOString().split('T')[0]
  },
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '支付流水',
  initForm: {},
  doCreate: api.createCouponUse,
  doUpdate: api.updateCouponUse,
  doDelete: api.deleteCouponUse,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  $table.value?.handleSearch()
})

const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    // 获取表格数据
    const { data: tableData } = await api.getOrderWater({
      ...queryItems.value,
      is_export:1
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    // 处理数据格式
    const exportData = tableData.map(item => ({
      单号: item.type_id,
      客户姓名: item.user_name,
      支付金额: item.money,
      支付时间: item.created_at,
      收银状态: item.pay_status === 1 ? '未收银' : '已收银',
      支付凭证: item.pay_voucher_image?.join('; ') || ''
    }))

    // 导出Excel
    exportToExcel(exportData, `支付流水_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}

const columns = [
  {
    title: '单号',
    key: 'type_id',
    width: 80,
    align: 'center',
  },
    {
    title: '客户姓名',
    key: 'user_name',
    width: 120,
    align: 'center',
    render(row) {
      return h(NFlex, {justify: "center",
        align: "center"},
        [h(NButton, {
          size: "small",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.user_name)
        })]
      )

    },
  },
    {
    title: '支付金额',
    key: 'money',
    width:100,
    align: 'center',
  },
{
    title: '支付时间',
    key: 'created_at',
    width:160,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '收银状态',
    key: 'pay_status',
    width:160,
    align: 'center',
    render(row) {
      if(row.pay_status === 1){
        return h(NTag, { type: 'error',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => '未收银' })
      }else{
        return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => '已收银' })
      }

    },
  },
  {
    title: '支付凭证',
    key: 'pay_voucher_image',
    align: 'left',
    width:250,
    ellipsis: { tooltip: true },
    render(row) {
      const images = row.pay_voucher_image ?? []
      const group = []
      for (let i = 0; i < images.length; i++)
        group.push(
            h(NImage,  { src: images[i],width: 40 ,height:40,style:"margin-right:2px;border-radius: 5px;"})
        )
      return h('span', group)
    },
  },


]

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}



</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer title="支付流水">
        <template #action>
          <NButton type="info" @click="handleExport">
            <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getOrderWater"
          :scroll-x="1200"

        >
          <template #queryBar>
            <QueryBarItem label="订单编号" :label-width="80">
              <NInput
                v-model:value="queryItems.type_id"
                clearable
                type="text"
                placeholder="订单编号"
                style="width: 200px;"
              />
            </QueryBarItem>
            <QueryBarItem label="客户姓名" :label-width="80">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="客户姓名/病历号/手机号"
                style="width: 200px;"
              />
            </QueryBarItem>
            <QueryBarItem label="付款时间" :label-width="70">
              <NDatePicker
                  v-model:value="datetimeRange"
                  type="datetimerange"
                  clearable
                  placeholder="请选择时间范围"
                  @update:value="handleDateRangeChange"
              />
            </QueryBarItem>
            <QueryBarItem label="收银状态" :label-width="70">
              <NSelect
                v-model:value="queryItems.pay_status"
                style="width: 200px;"
                :options="data.is_check_data"
                clearable
                label-field="name"
                    value-field="id"
                placeholder="选择审核状态"
              />
            </QueryBarItem>




          </template>
        </CrudTable>


      </CommonPage>


    </NLayoutContent>
  </NLayout>


  <!-- 业务页面 -->
</template>
